package com.superman.supermarket.client.utils;

import java.util.HashMap;
import java.util.Map;

import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.superman.mvpframe.client.ajax.PostManAsyncCallBack;
import com.superman.mvpframe.client.gin.XGinjector;
import com.superman.mvpframe.client.utils.StringUtils;
import com.superman.mvpframe.client.utils.XJsonUtil;

/**
 * 登录工具类
 * 
 * @author superman
 * @version 2018年8月28日上午11:21:14
 */
public class LoginUtils {

	/**
	 * 登录
	 * 
	 * @author superman
	 * @version 2018年8月28日 上午11:21:27
	 * @param callback
	 */
	public static void authLogin(final AsyncCallback<Void> callback) {
		final String code = Window.Location.getParameter("code");
		if (StringUtils.isEmpty(code)) {
			if (StringUtils.isEmpty(History.getToken()))
				// code空,hash空.缓存
				XGinjector.INSTANCE.getUserModel().clear();
			else
				// code空,hash不空,读用户数据
				XGinjector.INSTANCE.getUserModel().readFromCache();
			callback.onSuccess(null);
		} else {
			// 重复的code,不进行静默登录.
			if (AuthUtils.isCodeValid(code)) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("CODE", code);
				XGinjector.INSTANCE.getPostMan().post("user/login", map, new PostManAsyncCallBack() {

					@Override
					public void onBusinessError(String statusCode) {
						callback.onSuccess(null);
					}

					@Override
					public void onBusinessOK(String response) {
						XGinjector.INSTANCE.getUserModel().parse(XJsonUtil.getJOBody(response));

						XGinjector.INSTANCE.getUserModel().saveToCache();

						AuthUtils.pushUsedCode(code);

						callback.onSuccess(null);
					}

					@Override
					public void onHttpError(String fullPostUrl, int statusCode) {
						callback.onSuccess(null);
					}
				});
			} else {
				// 重复的code,目前认为是页面重载或者返回的操作.所以直接同步当前实例下用户的登录信息
				XGinjector.INSTANCE.getUserModel().readFromCache();
				callback.onSuccess(null);
			}
		}

	}

}
